import {InjectModel} from "nestjs-typegoose";
import {User} from "@libs/db/models/user.model";
import {Model} from "mongoose";
import {HttpException, HttpStatus, Injectable} from "@nestjs/common";
import {DocumentType} from "@typegoose/typegoose";
import {JwtService} from "@nestjs/jwt";
import {changeUserDto} from "./dto/change-user.dto";
import * as bcrypt from 'bcryptjs'
import {ConfigService} from "@nestjs/config";
import {EnvEnum} from "@app/common/enum/envEnum";

@Injectable()
export class AuthService {
  constructor(
      @InjectModel(User) private readonly UserModel: Model<User>,
      private readonly JwtService: JwtService,
      private readonly configService: ConfigService
  ) {
  }

  async register(data: User) {
    const findUser = await this.UserModel.findOne({username: data.username})
    if (findUser) {
      throw new HttpException('用户名已存在', HttpStatus.FORBIDDEN)
    }
    return await this.UserModel.create(data)
  }

  async login(user: DocumentType<User>) {
    const token = this.JwtService.sign({id: user._id})
    return {token}
  }

  async changeUser(dto: changeUserDto, user) {
    if (!dto.rawPassword && !dto.newPassword) {
      await this.UserModel.findByIdAndUpdate(user._id, dto);
    } else {
      const userInfo = await this.UserModel.findById(user._id).select('+password')
      const valid = bcrypt.compareSync(dto.rawPassword, userInfo.password)
      if (!valid) {
        throw new HttpException('旧密码错误', HttpStatus.FORBIDDEN)
      }
      dto.password = dto.newPassword
      await this.UserModel.findByIdAndUpdate(user._id, dto);
    }

    return this.UserModel.findById(user._id)
  }
}
